package com.wzl.policy.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

/**
 * sftp工具类
 *
 * @author weizhongli
 * @since 2022-08-25 19:04
 */
@Slf4j
@Component
public class SFtpUtil {

    /**
     * Session
     */
    private static Session session = null;
    /**
     * Channel
     */
    private static ChannelSftp channel = null;

    /**
     * 连接SFTP服务器
     * @param ip
     * @param port
     * @param username
     * @param password
     * @return
     */
    public boolean login(String ip, int port, String username, String password) {
        JSch jsch = new JSch();
        try {
            session = jsch.getSession(username, ip, port);
            session.setPassword(password);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            log.info("sftp session connected");

            log.info("opening channel");
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            log.info("connected successfully");
            return true;
        } catch (JSchException e) {
            log.error("sftp login failed", e);
            return false;
        }
    }

    /**
     * 登出sftp
     */
    public void logout() {
        if (channel != null) {
            channel.quit();
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        log.info("logout successfully");
    }

    /**
     * 获取指定sftp目录下的文件
     */
    public List<ChannelSftp.LsEntry> getFileList(String remotePath) {
        Vector<ChannelSftp.LsEntry> fileList = new Vector<ChannelSftp.LsEntry>();
        try {
            channel.cd(remotePath);
            Vector<ChannelSftp.LsEntry> lss = channel.ls("*");
            for (int i = 0; i < lss.size(); i++) {
                fileList.add(lss.get(i));
            }
        } catch (SftpException e) {
            e.printStackTrace();
            log.error("获取文件失败", e);
        }
        return fileList;
    }

    /**
     * sftp移动文件到指定目录
     */
    public boolean moveSftpFileToDir(String folder,String fromdir,String fileName, String todir) {
        boolean success = false;
        try {
            //如果目录不存在则创建目录
            boolean existDir = isExistDir(todir + "/" + folder);
            if(!existDir){
                channel.cd(todir);
                channel.mkdir(folder);
            }
            channel.rename(fromdir + "/" + folder + "/" + fileName, todir + "/" + folder + "/" + fileName);
            success = true;
        } catch (SftpException e) {
            e.printStackTrace();
            log.error("文件移动失败", e);
        }
        return success;
    }

    /**
     * 判断目录是否存在
     * @param path
     * @return
     */
    public boolean isExistDir(String path){
        boolean  isExist=false;
        try {
            SftpATTRS sftpATTRS = channel.lstat(path);
            isExist = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isExist = false;
            }
        }
        return isExist;
    }

    /**
     * 读取文件内容为List 每行作为一个List的节点
     */
    public List readFtpFile(String FileName, String remotePath) {
        List list = new ArrayList();
        try {
            InputStream in=channel.get(remotePath + "/" +FileName);
            list = readFileIntoList(in);
        } catch (SftpException e) {
            e.printStackTrace();
            log.error("文件读取失败", e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }


    /**
     * 从输入流中读取文件到List 每行作为一个List的节点
     *
     * @param inStream
     * @return
     * @throws IOException
     */
    public static List readFileIntoList(InputStream inStream) throws IOException {
        String line = null;
        List result = null;
        if (inStream != null) {
            result = new ArrayList();
            BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
            while ((line = in.readLine()) != null) {
                line = line.trim();
                if (line.length() > 0) {
                    result.add(line.trim());
                }
            }
            if (result.size() <= 0) {
            }
            in.close();
            inStream.close();
        }
        return result;
    }

    /**
     * 获取指定文件夹下面的文件夹
     * 列出SFTP服务器上面当前目录的所有的目录
     */
    public List<String> getFolderList(String remotePath) {

        ArrayList fileFolderList = new ArrayList();

        try {
            channel.cd(remotePath);
            Vector<ChannelSftp.LsEntry> lss = channel.ls("*");
            for (int i = 0; i < lss.size(); i++) {
                ChannelSftp.LsEntry lsEntry = lss.get(i);
                fileFolderList.add(lsEntry.getFilename());
            }
        } catch (SftpException e) {
            throw new RuntimeException(e);
        }

        return fileFolderList;
    }


    /**
     * 删除目录
     *
     * @param directory 要删除文件所在目录
     */
    public boolean deleteDir(String directory) {
        boolean success = false;
        try {
            channel.rmdir(directory);
            success = true;
        } catch (Exception e) {
            log.error("删除目录 directory=[" + directory + "] error : ", e);
        }
        return success;
    }


    public static void main(String[] args) {
        SFtpUtil aiSFtpUtil = new SFtpUtil();
        aiSFtpUtil.login("133.0.120.58",22,"bea","hello-JAVA-1");
        log.info("登录成功");
//        try {
//            List<ChannelSftp.LsEntry> fileList = aiSFtpUtil.getFileList("/home/bea/stream/work/20220825");
//            String filename = fileList.get(0).getFilename();
//            SftpATTRS attrs = fileList.get(0).getAttrs();
//            String[] ww = String.valueOf(attrs).split(" ");
//            String  timeStr = "";
//            for (int i = 4; i < ww.length; i++) {
//                timeStr += ww[i] + " ";
//            }
//            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
//            Date date = sdf.parse(timeStr);
//            String timesTamp = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
//            System.out.println(timeStr);
//            log.info("获取该文件下文件集合成功" + fileList);
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }
//        aiSFtpUtil.moveSftpFileToDir("20220825","/home/bea/stream/work","DUP.CUST_ZD.20220801.1012.012.txt","/home/bea/stream/error");
//        log.info("移动文件成功");
        List list = aiSFtpUtil.readFtpFile("DUP.ADJSQ.20220829.0002.027", "/home/bea/stream/work/20220826");
        System.out.println(list);

//        List<String> folderList = aiSFtpUtil.getFolderList("/home/bea/stream/work");
//        System.out.println(folderList);
//
//        boolean b = aiSFtpUtil.deleteDir("/home/bea/stream/work/20220826");
//        System.out.println(b);


        aiSFtpUtil.logout();
        log.info("退出登录成功");

    }


}